import { MarketingDepartment } from '../models/MarketingDepartment.js';
import { Student } from '../models/Student.js';

const marketingModel = new MarketingDepartment();
const studentModel = new Student();

export class MarketingController {
  // 获取市场部列表
  async getMarketingDepartments(req, res) {
    try {
      console.log('获取市场部列表，查询参数:', req.query);
      
      const departments = marketingModel.findAll();
      
      // 处理分页
      const page = parseInt(req.query.page) || 1;
      const pageSize = parseInt(req.query.pageSize) || 10;
      const startIndex = (page - 1) * pageSize;
      const endIndex = startIndex + pageSize;
      
      // 应用搜索过滤
      let filteredDepartments = [...departments];
      
      // 关键词搜索
      if (req.query.keyword) {
        const keyword = req.query.keyword.toLowerCase();
        filteredDepartments = filteredDepartments.filter(dept => 
          dept.name.toLowerCase().includes(keyword) ||
          dept.manager.toLowerCase().includes(keyword) ||
          dept.phone.toLowerCase().includes(keyword)
        );
      }
      
      // 关联学生数据
      const students = studentModel.findAll();
      const departmentsWithStats = filteredDepartments.map(dept => {
        const deptStudents = students.filter(student => student.marketingDepartment === dept.name);
        return {
          ...dept,
          studentCount: deptStudents.length,
          students: deptStudents
        };
      });
      
      // 分页
      const paginatedDepartments = departmentsWithStats.slice(startIndex, endIndex);
      
      // 构建响应
      const response = {
        data: paginatedDepartments,
        pagination: {
          current: page,
          pageSize: pageSize,
          total: departmentsWithStats.length,
          totalPages: Math.ceil(departmentsWithStats.length / pageSize)
        }
      };
      
      console.log('返回市场部数据:', {
        dataCount: paginatedDepartments.length,
        total: departmentsWithStats.length,
        pagination: response.pagination
      });
      
      res.json(response);
    } catch (error) {
      console.error('获取市场部列表失败:', error);
      res.status(500).json({ error: '获取失败' });
    }
  }

  // 创建市场部
  async createMarketingDepartment(req, res) {
    try {
      const { name, manager, phone, gender } = req.body;
      console.log('创建市场部:', { name, manager, phone, gender });
      
      if (!name || !manager || !phone || !gender) {
        return res.status(400).json({ error: '所有字段都为必填' });
      }

      const departments = marketingModel.findAll();
      
      // 检查名称是否已存在
      if (departments.find(m => m.name === name)) {
        return res.status(400).json({ error: '市场部名称已存在' });
      }

      const newItem = {
        name,
        manager,
        phone,
        gender
      };

      const createdDepartment = marketingModel.create(newItem);
      
      if (createdDepartment) {
        console.log('创建市场部成功:', createdDepartment);
        res.status(201).json(createdDepartment);
      } else {
        res.status(500).json({ error: '保存失败' });
      }
    } catch (error) {
      console.error('创建市场部失败:', error);
      res.status(500).json({ error: '创建失败' });
    }
  }

  // 更新市场部
  async updateMarketingDepartment(req, res) {
    try {
      const { id } = req.params;
      const { name, manager, phone, gender } = req.body;
      console.log('更新市场部:', id, { name, manager, phone, gender });

      const departments = marketingModel.findAll();
      
      // 检查名称是否被其他部门使用
      if (departments.find(m => m.name === name && m.id !== parseInt(id))) {
        return res.status(400).json({ error: '市场部名称已被其他部门使用' });
      }

      const updatedDepartment = marketingModel.update(id, {
        name,
        manager,
        phone,
        gender
      });

      if (updatedDepartment) {
        console.log('更新市场部成功:', updatedDepartment);
        res.json(updatedDepartment);
      } else {
        res.status(404).json({ error: '市场部不存在' });
      }
    } catch (error) {
      console.error('更新市场部失败:', error);
      res.status(500).json({ error: '更新失败' });
    }
  }

  // 删除市场部
  async deleteMarketingDepartment(req, res) {
    try {
      const { id } = req.params;
      console.log('删除市场部:', id);
      
      const departments = marketingModel.findAll();
      const students = studentModel.findAll();
      
      // 检查是否有学生关联此市场部
      const department = departments.find(m => m.id === parseInt(id));
      if (department) {
        const relatedStudents = students.filter(student => student.marketingDepartment === department.name);
        if (relatedStudents.length > 0) {
          return res.status(400).json({ 
            error: `无法删除，该市场部下还有 ${relatedStudents.length} 名学生` 
          });
        }
      }

      const success = marketingModel.delete(id);
      
      if (success) {
        console.log('删除市场部成功');
        res.json({ message: '删除成功' });
      } else {
        res.status(404).json({ error: '市场部不存在' });
      }
    } catch (error) {
      console.error('删除市场部失败:', error);
      res.status(500).json({ error: '删除失败' });
    }
  }
}